package controllers;

import connectivity.Dbmanager;
import connectivity.QueryManager;
import java.io.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;
import models.DigitalClassQuestion;

public class AnswerQuestionController extends HttpServlet {

    private int questionID;
    private DigitalClassQuestion question = new DigitalClassQuestion();
    private boolean questionAnswered = false;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Dbmanager dbManager = new Dbmanager();
        DigitalClassQuestion tempQuestion = new DigitalClassQuestion();
        dbManager.openConnection();
        QueryManager queryManager = new QueryManager(dbManager);
        HttpSession sessie = request.getSession();
        if(questionAnswered == false) {
            question = (DigitalClassQuestion) sessie.getAttribute("viewedQuestion");
            questionID = question.getQuestionID();
        }
        ArrayList questions = new ArrayList();
        questions = queryManager.getQuestionsAnswered(1);
        if(questionAnswered == false) {
            ArrayList questionsNotAnswered = new ArrayList();
            questionsNotAnswered = queryManager.getQuestions(1);
            questions.addAll(questionsNotAnswered);
        }
        dbManager.closeConnection();
        for (int i = 0; i < questions.size(); i++) {
            tempQuestion = (DigitalClassQuestion) questions.get(i);
            if (tempQuestion.getQuestionID() == questionID) {
                question = tempQuestion;
            }
        }
        sessie.setAttribute("viewedQuestion", question);
        questionAnswered = false;
        dbManager.closeConnection();
        RequestDispatcher dispatcher = request.getRequestDispatcher("/viewAnswer.jsp");
        dispatcher.forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        
        Dbmanager dbManager = new Dbmanager();
        dbManager.openConnection();
        QueryManager queryManager = new QueryManager(dbManager);
        HttpSession sessie = request.getSession();
        String answer;
        question = (DigitalClassQuestion) sessie.getAttribute("viewedQuestion");
        questionID = question.getQuestionID();
        answer = request.getParameter("questionAnswer");
        queryManager.answerQuestion(questionID, answer);
        questionAnswered = true;
        dbManager.closeConnection();
        doGet(request, response);
    }
}
